<?php

if(!defined('OI')) {
			
	print '<h1>Access Error</h1>Sorry, this file can not be accessed directly, this is strictly forbidden!';
	exit();
				
}

class Database {

	# Public variable
	public $totalRan = 0;
	public $affectedRows = 0;
	public $numberRows = 0;
	public $insertID = 0;
	
	# Private variables
	private $config;
	private $result = NULL;
	private $debugRequest = false;	
	
	# Database debug details
	private $debug = array(
		'lastQuery' => '',
		'lastError' => '',
		'lastResult' => NULL,
		'columnInformation' => NULL,
		'capturedErrors' => NULL,
		'queryHistory' => NULL
	);
	
	public function getDebug() {
		
		return $this->debug;
		
	}
	
	/*
	 * Constructor: Store instance of DigitalUniversity config
	 * 	- Attempt to connect to the desired database using the
	 *		  specified details
	*/
	public function __construct(&$config, $debugRequest = false){		
		
		# Store configuration	
		$this->config =& $config;
		$this->debugRequest = true;//$debugRequest;
				
		# Define SQL details
		$dbuser = $this->config['sql_user'];
		$dbpassword = $this->config['sql_pass']; 
		$dbname = $this->config['sql_name'];
		$dbhost = $this->config['sql_host'];
	
		# Local variable, error check
		$connectError = false;
				
		if(empty($dbuser) || empty($dbname)){
			
			$connectError = true;
			$this->saveError('Connect #1');
						
		} elseif(!$this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true)){
						
			$connectError = true;
			$this->saveError('Connect #2');
								
		} elseif(!$this->dbh) {
						
			$connectError = true;
			$this->saveError('Connect #3');
		
		} elseif(!@mysql_select_db($dbname, $this->dbh)) {
			
			if (!$str = @mysql_error($this->dbh))
			
			$connectError = true;
			$this->saveError('Connect #4');
				
		}
		
		/*	
		 * Connection error: Do not terminate Swoova
		*/
		if($connectError) {
		
			$this->saveError('<span style="font-family: Arial;font-size: 14px;"><h1>Technical Difficulties</h1>Digital University is currently experiencing technical difficulties.<p>'.$this->debug['lastError'].'</p></span>');
						
			exit($this->debug['lastError']);			
			
		}
										
	}

	/*
	 * checkConnected: Check if there is a database connection present
	*/
	private function checkConnected() {
	
		if(!isset($this->dbh) || $this->dbh == NULL){
			
			return false;
			
		} else {
			
			return true;
			
		}
		
	}

	/*
	 * saveError: Error handling to save the latest recorded query error
	 *
	 * @param errorString - The result error message
	*/
	private function saveError($errorString){
	
		# Store last error
		$this->debug['lastError'] = $errorString;

		# Store in captured errors
		$this->debug['capturedErrors'][] = array(
			'error' => $errorString,
			'query' => $this->debug['lastQuery']
		);
					
	}
	
	/*
	 * getVar: Given a query, returns a single tuple or value from a column.
	 *
	 * @param query - The SQL query to execture
	 * @param x - The record to select
	 * @param y - The column to select
	*/
	public function getVar($query = NULL, $x = 0, $y = 0){

		if($query){
		
			$this->query($query);
			
		}

		if(!empty($this->debug['lastResult'][$y])){
		
			$values = array_values(get_object_vars($this->debug['lastResult'][$y]));
			
		}

		return (!empty($values[$x]) ? $values[$x] : NULL);
		
	}

	/*
	 * getRow: Given a query, return a record of results
	 *
	 * @param query - The SQL query to execture
	 * @param y - The row to select from the results
	*/
	function getRow($query = NULL, $y = 0){

		if($query){
		
			$this->query($query);
			
		}
		
		if(!empty($this->debug['lastResult'])) {
			
			return (!empty($this->debug['lastResult'][$y]) ? get_object_vars($this->debug['lastResult'][$y]) : NULL);
		
		} else {
			
			return NULL;
		
		}
				
	}

	/*
	 * getResults: Given a query, return an array of results
	 *
	 * @param query - The SQL query to execture
	 * @param cacheResult - Store the query in the cache or not
	 * @param cacheTime - If we want to store in cache, how long for (integer or timestamp)
	*/
	function getResults($query = NULL){
			
		# Execute SQL query				
		$numberRows = $this->query($query);
					
		# Check results		
		if(!empty($this->debug['lastResult'])) {
				
			# Store results										
			foreach($this->debug['lastResult'] as $k => $v){

				$newArray[$k] = get_object_vars($v);
					
			}
			
			# Return results			
			return $newArray;
					
		} else {
			
			return '';
				
		}

	}
						
	/*
	 * query: Execute the provded SQL query
	 *
	 * @param query - The query string
	 *
	 * @return numberRows - The number of rows found in the query
	 * @return false - If an error occurs
	*/
	function query($query){

		# Clean variables
		$query = trim($query);
		
		# Clean results	
		$this->clean();
			
		# Increment counter
		$this->totalRan++;
			
		# Save last query			
		$this->debug['lastQuery'] = $query;
		
		# No database connection
		if($this->checkConnected() === false) {
			
			$this->saveError('<span style="font-family: Arial;font-size: 14px;"><h1>Technical Error</h1>We are currently experiecing technical difficulties and will be back shortly</span>');				
			return false;
				
		}

		# Fetch results
		$this->result = @mysql_query($query, $this->dbh);
		
		# Add query to history
		if($this->debugRequest) {
			
			$this->debug['queryHistory'][] = $query;
			
		}
				
		# MySQL error
		if($str = @mysql_error($this->dbh)){
				
			# Store error							
			$this->saveError($str);
				
			# Return error																							
			return false;
										
		}
		
		# Type of query
		if(preg_match("/^(insert|delete|update|replace)\s+/i", $query)){
		
			# Store rows affected	
			$this->affectedRows = @mysql_affected_rows();
			$value = $this->affectedRows;
			
			# Get insert/update ID
			if(preg_match("/^(insert|replace)\s+/i",$query)){
			
				$this->insertID = @mysql_insert_id($this->dbh);
				
			}
						
		} else {
		
			/*
			 * Get result column information.
			 * We only want to do this on a debug request.
			*/
			if($this->debugRequest) {
				
				$i = 0;				
				while($i < @mysql_num_fields($this->result)){
				
					$this->debug['columnInformation'][$i] = @mysql_fetch_field($this->result);
					$i++;
						
				}
			
			}

			# Store last result
			while($row = @mysql_fetch_object($this->result)){
			
				$this->debug['lastResult'][$this->numberRows] = $row;
				
				# Return rows
				$this->numberRows++;
				
			}

			# Free MySQL result
			@mysql_free_result($this->result);
						
		}
		
		return $this->numberRows;

	}
	
	/*
	 * clean: Remove the last stored details
	*/	
	private function clean() {
	
		# Result variables
		$this->numberRows = 0;	
		$this->affectedRows = 0;	
		
		# Remove column information
		if($this->debugRequest && (!empty($this->debug['columnInformation']))) {
			$this->debug['columnInformation'] = '';
		}
		
		# Remove lastQuery
		$this->debug['lastQuery'] = '';
		$this->debug['lastResult'] = NULL;
		
	}
	
	/*
	 * closeConnect: Disconnect our database and exit
	*/	
	public function closeConnect() {
		
		# Check connected
		if($this->checkConnected()) {
			
			mysql_close($this->dbh);	
		
		}
		
	}
				
}

?>
